/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.productos.gui;

import java.awt.BorderLayout;
import java.io.IOException;
import java.util.Collection;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import org.marcelo.agro.core.DynamicLookup;
import org.marcelo.agro.entidades.Productos;
import org.marcelo.agro.productos.actions.AgregarProductosActions;
import org.marcelo.comun.habilidades.Creable;
import org.netbeans.api.actions.Editable;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.marcelo.agro.productos.gui//ListaProductos//EN",
autostore = false)
@TopComponent.Description(preferredID = "ListaProductosTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.marcelo.agro.productos.gui.ListaProductosTopComponent")
@ActionReference(path = "Menu/Ver" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ListaProductosAction",
preferredID = "ListaProductosTopComponent")
@Messages({
    "CTL_ListaProductosAction=ListaProductos",
    "CTL_ListaProductosTopComponent=ListaProductos Window",
    "HINT_ListaProductosTopComponent=This is a ListaProductos window"
})
public final class ListaProductosTopComponent extends TopComponent {
    
    
    private final String VENTANA_AGREGAR = "AgregarProductosTopComponent"; 
    
    private Creable creable = new Creable() {

        @Override
        public void doNew() {
            //Cuando se llama a new 
//            Productos producto = DynamicLookup.getDefault().lookup(Productos.class);
//            if (producto != null){
//                DynamicLookup.getDefault().remove(producto);
//            }
//            TopComponent tc = WindowManager.getDefault().findTopComponent(VENTANA_AGREGAR);
//            tc.open();
//            tc.requestActive();
//            DynamicLookup.getDefault().add(producto);
            AgregarProductosActions apa = new AgregarProductosActions();
            apa.actionPerformed(null);
        }
    };
    
    private Editable edit = new Editable() {

        @Override
        public void edit() {
//            TopComponent tc = WindowManager.getDefault().findTopComponent(VENTANA_AGREGAR);
//            tc.open();
//            tc.requestActive();
            Productos producto = DynamicLookup.getDefault().lookup(Productos.class);
            AgregarProductosActions apa = new AgregarProductosActions(producto);
            apa.actionPerformed(null);
            
        }
    };
    
    InstanceContent content = new InstanceContent();
    AbstractLookup lookup = new AbstractLookup(content);
    
    public ListaProductosTopComponent() {
        initComponents();
        setName(Bundle.CTL_ListaProductosTopComponent());
        setToolTipText(Bundle.HINT_ListaProductosTopComponent());
        jPanel1.setLayout(new BorderLayout());    
        resultProductos = DynamicLookup.getDefault().lookupResult(Productos.class);
        associateLookup(lookup);
        

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 380, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 278, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        initFX();
        jPanel1.add(jFXPanel,BorderLayout.CENTER);
        content.add(creable);
        
        
        resultProductos.addLookupListener(ll);
        ll.resultChanged(new LookupEvent(resultProductos));
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        jPanel1.remove(jFXPanel);
        jFXPanel = null; 
        content.remove(creable);
        resultProductos.removeLookupListener(ll);
        
        
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private JFXPanel jFXPanel;
    private void initFX() {
       Platform.setImplicitExit(false);
        jFXPanel = new JFXPanel();
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                AnchorPane root;
                try {
                    root = FXMLLoader.load(getClass().getResource("listaProductos.fxml")) ;
                    
                   
                    Scene scene = new Scene(root);
                    
//                    scene.getStylesheets().add("gui.css");
                                        
                    jFXPanel.setScene(scene);
                    
                }
                catch (IOException ioe) {
                //ignorar por motivos de prueba
                }
            }
        });
    
    }
    
    private Lookup.Result<Productos> resultProductos;
    /** Este elemento escuchara los cambios en el loouk para poder agregar o quitar
     *  el editable al lookup del sistema
     */
    private final LookupListener ll = new LookupListener() {

        @Override
        public void resultChanged(LookupEvent ev) {
            //Cuando se selecciona un elemento, se habilitara el boton editar
            if (ev.getSource().equals(resultProductos)) {
                Collection<? extends Productos> listProductos = resultProductos.allInstances();
                if (listProductos.isEmpty()) {
                    content.remove(edit);
                }
                else {
                    content.add(edit);
                }
            }
            // cuando se deselecciona se eliminara del content entonces no se podra editar
        }
    };
    
}
